define(['jquery', 'bootstrap', 'upload', 'validator', 'bootstrap-switch'], function ($, undefined, Upload, Validator) {
    var Form = {
        config: {
        },
        api: {
            submit: function (form, onBeforeSubmit, onAfterSubmit) {
                if (form.size() == 0)
                    return Toastr.error("表单未初始化完成,无法提交");
                //提交前事件
                var beforeSubmit = form.data("before-submit");
                //元素绑定函数
                if (beforeSubmit && typeof Form.api.custom[beforeSubmit] == 'function') {
                    if (!Form.api.custom[beforeSubmit].call(form)) {
                        return false;
                    }
                }
                //自定义函数
                if (typeof onBeforeSubmit == 'function') {
                    if (!onBeforeSubmit.call(form)) {
                        return false;
                    }
                }
                var type = form.attr("method").toUpperCase();
                type = type && (type == 'GET' || type == 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                var params = form.serializeObject();
                params.password && (params.password = hex_md5(params.password));
                Util.api.ajax({
                    type: type,
                    url: url,
                    data: JSON.stringify(params),
                }, function (data) {
                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    //成功提交后事件
                    var afterSubmit = form.data("after-submit");
                    data = data ? data : params;
                    //元素绑定函数
                    if (afterSubmit && typeof Form.api.custom[afterSubmit] == 'function') {
                        if (!Form.api.custom[afterSubmit](data)) {
                            return false;
                        }
                    }
                    //自定义函数
                    if (typeof onAfterSubmit == 'function') {
                        if (!onAfterSubmit(data)) {
                            return false;
                        }
                    }
                });
                return false;
            },
            bindevent: function (form, onBeforeSubmit, onAfterSubmit) {
            	//本地验证未通过时提示
            	form.data("validator-options", {
                    invalid: function (form, errors) {
                        $.each(errors, function (i, j) {
                            Toastr.error(j);
                        });
                    },
                    target: '#errtips'
                });
                //绑定表单事件
                form.validator($.extend({
                    validClass: 'has-success',
                    invalidClass: 'has-error',
                    bindClassTo: '.form-group',
                    formClass: 'n-default n-bootstrap',
                    msgClass: 'n-right',
                    stopOnError: true,
                    display: function (elem) {
                        return $(elem).closest('.form-group').find(".control-label").text().replace(/\*/, '').replace(/\:{0}：/, '').trim();
                    },
                    target: function (input) {
                        var $formitem = $(input).closest('.form-group'),
                                $msgbox = $formitem.find('span.msg-box');
                        if (!$msgbox.length) {
                            return [];
                        }
                        return $msgbox;
                    },
                    valid: function (ret) {
                        //验证通过提交表单
                    	if(form.attr('action')) {
                            Form.api.submit($(ret), onBeforeSubmit, function (data) {
                                if (typeof onAfterSubmit == 'function') {
                                    if (!onAfterSubmit(data)) {
                                        return false;
                                    }
                                }
                                //提示及关闭当前窗口
                                parent.Toastr.success(__('Operation completed'));
                                parent.$(".btn-refresh").trigger("click");
                                try {
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }catch(e){}
                            });
                    	}
                        return false;
                    }
                }, form.data("validator-options") || {}));
                
                //移除提交按钮的disabled类
                $(".layer-footer .btn.disabled", form).removeClass("disabled").attr('disabled', false);
                $('[type="submit"].btn.disabled', form).removeClass("disabled").attr('disabled', false);

                //绑定select元素事件
                if ($(".selectpicker", form).size() > 0) {
                    require(['bootstrap-select', 'bootstrap-select-lang'], function () {
                        $('.selectpicker', form).selectpicker();
                    });
                }
                $.fn.bootstrapSwitch.defaults.size = 'small';
                $.fn.bootstrapSwitch.defaults.onColor = 'success';
                $(".switch").bootstrapSwitch();

                //绑定selectpage元素事件
                if ($(".selectpage", form).size() > 0) {
                    require(['selectpage'], function () {
                        $('.selectpage', form).selectPage({
                            source: 'ajax/selectpage',
                        });
                    });
                    //给隐藏的元素添加上validate验证触发事件
                    $(form).on("change", ".selectpage-input-hidden", function () {
                        $(this).trigger("validate");
                    });
                }

                //绑定cxselect元素事件
                if ($("[data-toggle='cxselect']").size() > 0) {
                    require(['cxselect'], function () {
                        $.cxSelect.defaults.jsonName = 'name';
                        $.cxSelect.defaults.jsonValue = 'value';
                        $.cxSelect.defaults.jsonSpace = 'data';
                        $("[data-toggle='cxselect']").cxSelect();
                    });
                }

                //绑定日期时间元素事件
                if ($(".datetimepicker", form).size() > 0) {
                    require(['bootstrap-datetimepicker'], function () {
                        $('.datetimepicker', form).parent().css('position', 'relative');
                        $('.datetimepicker', form)
                                .datetimepicker({
                                	language: 'zh-CN',
                                    icons: {
                                        time: 'fa fa-clock-o',
                                        date: 'fa fa-calendar',
                                        up: 'fa fa-chevron-up',
                                        down: 'fa fa-chevron-down',
                                        previous: 'fa fa-chevron-left',
                                        next: 'fa fa-chevron-right',
                                        today: 'fa fa-history',
                                        clear: 'fa fa-trash',
                                        close: 'fa fa-remove'
                                    },
                                    minView: $('.datetimepicker', form).attr('data-date-format').length == 10 ? 'month' : 'hour',
                                    todayBtn: true,
                                    autoclose: true,
                                }).on('changeDate', function(ev) {
                                    $('.datetimepicker', form).trigger("validate");
                                });
                    });
                }

                //绑定summernote事件
                if ($(".summernote", form).size() > 0) {
                    require(['summernote'], function () {
                        $(".summernote", form).each(function(){
                        	$(this).summernote({
	                            height: $(this).attr('data-height') ? $(this).attr('data-height') : 250,
	                            lang: 'zh-CN',
	                            fontNames: [
	                                'Arial', 'Arial Black', 'Serif', 'Sans', 'Courier',
	                                'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande',
	                                "Open Sans", "Hiragino Sans GB", "Microsoft YaHei",
	                                '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆',
	                            ],
	                            fontNamesIgnoreCheck: [
	                                "Open Sans", "Microsoft YaHei",
	                                '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆'
	                            ],
	                            dialogsInBody: true,
	                            callbacks: {
	                                onChange: function (contents) {
	                                    $(this).val(contents);
	                                    $(this).trigger('change');
	                                },
	                                onInit: function () {
	                                },
	                                onImageUpload: function (files) {
	                                    var that = this;
	                                    //依次上传图片
	                                    for (var i = 0; i < files.length; i++) {
	                                        Upload.api.send(files[i], function (url) {
	                                            $(that).summernote("insertImage", url, 'filename');
	                                        });
	                                    }
	                                }
	                            }
	                        });
	                    });
                    })
                }

                //绑定plupload上传元素事件
                if ($(".plupload", form).size() > 0) {
                    Upload.api.plupload();
                }

                //绑定fachoose选择附件事件
                if ($(".fachoose", form).size() > 0) {
                    $(document).on('click', ".fachoose", function () {
                        var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
                        var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
                        Util.api.open("general/attachment/select?callback=refreshchoose&element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype, __('Choose'));
                        return false;
                    });

                    //刷新选择的元素
                    window.refreshchoose = function (id, data, multiple) {
                        var input_id = $("#" + id).data("input-id");
                        if (multiple) {
                            var urlArr = [];
                            var inputObj = $("#" + input_id);
                            if (inputObj.val() != "") {
                                urlArr.push(inputObj.val());
                            }
                            urlArr.push(data.url);
                            inputObj.val(urlArr.join(",")).trigger("change");
                        } else {
                            $("#" + input_id).val(data.url).trigger("change");
                        }
                        Layer.closeAll();
                    };
                }
            },
            fill: function(form, url, id, callback) {
    			$('.loading').show();
    			Util.api.ajax({
            		type: 'PUT',
            		url: url,
            		data: JSON.stringify({id: id})
            	}, function(data) {
        			form.autofill(data);
        			callback && callback(data);
            	});
            },
            custom: {}
        },
        init: function() {
    		$.fn.serializeObject = function(){
	    		var obj = {};
	    		$.each(this.serializeArray(), function(index){
	    			var v = this['value'];
	    			try{
	    				var t = JSON.parse(v);
	    				if(typeof(t) == 'object') {
	    					v = t;
	    				}
	    			}catch(e){}
	    		   if(this['name'].indexOf('.') > -1) {
	    			   var n = this['name'].split('.');
	    			   if(!obj[n[0]]) {
	    					obj[n[0]] = {};
		    			 	obj[n[0]][n[1]] = v;
	    			   } else {
	    				   if(obj[n[0]] instanceof Array) {
	    					   if(obj[n[0]][obj[n[0]].length - 1][n[1]]) {
	    						   var o = {};
	    						   o[n[1]] = v;
	    						   obj[n[0]].push(o);
	    					   } else {
	    						   obj[n[0]][obj[n[0]].length -1][n[1]] = v;
	    					   }
	    				   } else {
	    					   if(obj[n[0]][n[1]]) {
	    						   var o = {};
	    						   o[n[1]] = v;
		    					   obj[n[0]] = [obj[n[0]], o];
	    					   } else {
	    						   obj[n[0]][n[1]] = v;
	    					   }
	    				   }
	    			   }
	    		   } else {
	    			   if(obj[this['name']]) {
	    				   if(obj[this['name']] instanceof Array) {
	    					   obj[this['name']].push(v);
	    				   } else {
	    					   obj[this['name']] = [obj[this['name']], v];
	    				   }
	    			   } else {
	    				   obj[this['name']] = v;
	    			   }
	    		   }
	    	   });
	    		return obj;
	    	};
    	},
    };
    Form.init();
    return Form;
});